import router from "./index";
import { useLayoutStore } from "~/store/modules/layout";
import { useUserStore } from "~/store/modules/user";
import { getToken, getQueryString, removeURLParameter } from "~/utils/auth";
import { useRoleListStore } from "~/store/modules/role";

const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
	const hasToken = getToken();
	if (!hasToken) {
		if (to.path === "/login") {
			next();
		} else {
			const layoutStore = useLayoutStore();
			const userStore = useUserStore();
			const roleListStore = useRoleListStore();
			const hasRoles =
				layoutStore.rolesMenu && layoutStore.rolesMenu.length > 0;
			if (hasRoles) {
				next();
			} else {
				try {					
					await layoutStore.getRoleMenu();
					await userStore.getUserInfo();
					// await roleListStore.getAllRoleResourceByUserId();
					next({ ...to, replace: true });
				} catch (error) {
					// await userStore.resetStateToken();
					// window.open(
					// 	`${portalUrl}/login?redirect=${encodeURIComponent(
					// 		removeURLParameter(location.href, "code")
					// 	)}`,
					// 	"_self"
					// );
					next({ ...to, replace: true });
				}
				roleListStore.initialize();

				const roleCode = userStore.userInfo.userCode.toString();
				const roleList = roleCode.split(",");
			}
		}
	} else if (whiteList.indexOf(to.path) > -1) {
		next();
	} else {
		next("/login");
	}
});
